---
title: Clipboard
description: Using the clipboard machine in your project.
package: "@zag-js/clipboard"
---

The clipboard machine allows users to quickly copy content to clipboard.

<Resources pkg="@zag-js/clipboard" />

<Showcase id="Clipboard" />

## Installation

To use the clipboard machine in your project, run the following command in your
command line:

<CodeSnippet id="clipboard/installation.mdx" />

## Anatomy

To set up the clipboard correctly, you'll need to understand its anatomy and how
we name its parts.

> Each part includes a `data-part` attribute to help identify them in the DOM`.

<Anatomy id="clipboard" />

## Usage

First, import the clipboard package into your project

```jsx
import * as clipboard from "@zag-js/clipboard"
```

The clipboard package exports two key functions:

- `machine` — The state machine logic for the clipboard widget.
- `connect` — The function that translates the machine's state to JSX attributes
  and event handlers.

> You'll also need to provide a unique `id` to the `useMachine` hook. This is
> used to ensure that every part has a unique identifier.

Next, import the required hooks and functions for your framework and use the
clipboard machine in your project 🔥

<CodeSnippet id="clipboard/usage.mdx" />

### Setting the clipboard value

You can set the value to copy by passing a `value` prop to the `machine`
context.

```jsx {2}
const service = useMachine(clipboard.machine, {
  value: "Hello, world!",
})
```

### Listening to copy events

When the value is copied to the clipboard, the `onStatusChange` event is fired.
You can listen to this event and perform any action you want.

```jsx {2}
const service = useMachine(clipboard.machine, {
  onStatusChange: (details) => {
    console.log("Copy status changed to", details.copied)
  },
})
```

### Checking if the value is copied

Use the `api.copied` property to check if the value is copied to the clipboard.

```jsx {2}
const api = clipboard.connect(service)

if (api.copied) {
  console.log("Value is copied to the clipboard")
}
```

### Changing the timeout

By default, the clipboard machine will automatically reset the state to `idle`
after `3000ms`. You can change this timeout by passing a `timeout` option to the
`machine` context.

```jsx {2}
const service = useMachine(clipboard.machine, {
  timeout: 5000,
})
```

## Styling guide

Earlier, we mentioned that each clipboard part has a `data-part` attribute added
to them to select and style them in the DOM.

```css
[data-scope="clipboard"][data-part="root"] {
  /* styles for the root part */
}
```

## Methods and Properties

### Machine Context

The clipboard machine exposes the following context properties:

<ContextTable name="clipboard" />

### Machine API

The clipboard `api` exposes the following methods:

<ApiTable name="clipboard" />

### Data Attributes

<DataAttrTable name="clipboard" />
